package com.huitone.smspfm.interfacz.core.listener;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.channels.FileLock;

import com.bin.common.utils.StringUtils;

/**   
* @Title ShareMemoryRead.java 
* @Package com.huitone.quartz.share 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年10月11日 下午7:13:45 
* @version V1.0   
*/
public class ShareMemoryOpts {
	
	private RandomAccessFile raf = null;
	private FileChannel fc = null;
	private MappedByteBuffer mbb = null;
	
	public ShareMemoryOpts(String memoryFile, long memorySize) throws IOException {
		raf  = new RandomAccessFile(memoryFile,"rw"); 
		fc = raf.getChannel();
		mbb = fc.map(MapMode.READ_WRITE, 0, memorySize);
	}
	
	public String read(int offset, int limit) throws IOException {
		
		byte[] bytes = new byte[(limit - offset)];
		
		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = mbb.get(i);
        }
		
		mbb.clear();
		
		return new String(bytes, "utf-8").trim();
	}
	
	public synchronized String readThenReset(int offset, int limit) throws IOException {
		String result = read(offset, limit);
		if (!StringUtils.isEmpty(result)) {
			reset();
		}
		return result;
	}
	
	public synchronized void write(String string) throws IOException {
		
		FileLock tryLock = fc.tryLock();
		
		if (tryLock != null) {
			
			byte[] bytes = StringUtils.toString(string).getBytes("utf-8");
			
			for (int i = 0; i < bytes.length; i++) {
				mbb.put(bytes[i]);
	        }
			
			mbb.clear();
			
			tryLock.release();
			
		} else {
			System.out.println("文件被锁定了");
		}
	}
	
	public synchronized void reset() throws IOException {
		
		FileLock tryLock = fc.tryLock();
		
		if (tryLock != null) {
			
			long size = fc.size();
			
			for (int i = 0; i < size; i++) {
				mbb.put((byte)0);
	        }
			
			mbb.clear();
			
			tryLock.release();
			
		} else {
			System.out.println("文件被锁定了");
		}
	}
	
	public synchronized void reset(int offset, int limit) throws IOException {
		
		FileLock tryLock = fc.tryLock();
		
		if (tryLock != null) {
			
			for (int i = offset; i < limit + 1; i++) {
				mbb.put(i, (byte)0);
	        }
			
			mbb.clear();
			
			tryLock.release();
			
		} else {
			System.out.println("文件被锁定了");
		}
	}
}
